﻿#if !NETFRAMEWORK
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;
using WebSelfHost.Utility.Operator;


namespace WebSelfHost.Web.Filters
{
    /// <summary>
    /// 表示一个特性，该特性用于标识用户是否需要登陆。
    /// </summary>
    public class LoginCheckedAttribute : ActionFilterAttribute
    {
        public bool Ignore { get; set; }
        public LoginCheckedAttribute(bool ignore = true)
        {
            Ignore = ignore;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!Ignore)
            {
                return;
            }

            if (OperatorProvider.Instance.GetCurrent(filterContext.HttpContext.Request) == null)
            {
                //StringBuilder script = new StringBuilder();
                //script.Append("<script>top.location.href = '/account/login';</script>");
                //filterContext.Result = new ContentResult() { Content = script.ToString() };
                //filterContext.HttpContext.Response.//Write("<script>top.location.href = '/account/login'</script>");
                filterContext.HttpContext.Response.Redirect("/account/login");
            }
        }
    }
}
#else
using WebSelfHost.Utility.Operator;
using System;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebSelfHost.Web.Filters
{
    /// <summary>
    /// 表示一个特性，该特性用于标识用户是否需要登陆。
    /// </summary>
    public class LoginCheckedAttribute : ActionFilterAttribute
    {
        public bool Ignore { get; set; }
        public LoginCheckedAttribute(bool ignore = true)
        {
            Ignore = ignore;
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!Ignore)
            {
                return;
            } 
            if (OperatorProvider.Instance.GetCurrent(actionContext.Request) == null)
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage();
                actionContext.Response.StatusCode = System.Net.HttpStatusCode.Redirect; 
                string originalString = actionContext.Request.RequestUri.OriginalString;
                string pathAndQuery = actionContext.Request.RequestUri.PathAndQuery;
                string baseUrl = originalString.Substring(0, originalString.IndexOf(pathAndQuery));
                actionContext.Response.Headers.Location = new Uri(baseUrl + "/account/login");
            }
        }
    }
}
#endif